package com.derive.education_service.web.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.derive.education_service.common.global.Paper;
import com.derive.education_service.common.global.ResponseMessage;
import com.derive.education_service.entity.Agent;
import com.derive.education_service.entity.User;
import com.derive.education_service.mapper.AgentMapper;
import com.derive.education_service.mapper.UserMapper;
import com.derive.education_service.utils.MyFileUtils;
import com.derive.education_service.web.user.bean.dto.QueryParam;
import com.derive.education_service.web.user.bean.dto.UserAddDto;
import com.derive.education_service.web.user.bean.dto.UserUpDto;
import com.derive.education_service.web.user.bean.vo.UserVo;
import com.derive.education_service.web.user.service.UserService;
import com.derive.education_service.web.wechat.service.WxApiService;
import com.vdurmont.emoji.EmojiParser;
import lombok.extern.slf4j.Slf4j;
import org.dozer.Mapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 实现平台用户接口
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private Mapper dozerMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AgentMapper agentMapper;

    @Autowired
    private WxApiService wxApiService;

    @Autowired
    private MyFileUtils myFileUtils;

    /**
     * 客户注册
     * 微信授权登录后根据微信基本信息默认调用该接口注册登录
     * 注册前判断是否已有该用户
     *
     * @param userAddDto
     * @return
     */
    @Override
    public boolean addUserInfo(UserAddDto userAddDto) {
        String nickName = EmojiParser.parseToAliases(userAddDto.getNickName()); // 将表情转为字符
        userAddDto.setNickName(nickName); // 设置回去
        User user = dozerMapper.map(userAddDto, User.class);
        // 校验用户是否存在
        User checkUser = wxApiService.checkUser(userAddDto.getWxOpenId());
        if (checkUser != null) {
            // 已存在用户
            return false;
        }
        // 填充数据
        if (userAddDto.getYqOpenId() == null || userAddDto.getYqOpenId().isEmpty()) {
            user.setYqOpenId("oJgFn5YI5Eag3kyRzjKvgKefLOiU"); // 默认放我的
        }
        user.setIsState(true);
        user.setAdminId(0); // 0表示自己注册
        user.setUserTag(2); // 默认普通学员
        user.setCreateTime(new Date());
        // 执行新增
        int row = userMapper.insert(user);
        return row <= 0 ? false : true;
    }

    /**
     * 查看客户详细信息 -- 根据openId
     * error：不存在用户信息
     *
     * @param openId
     * @return
     */
    @Override
    public ResponseMessage getUserInfoByOpenId(String openId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("wx_open_id", openId);
        User user = userMapper.selectOne(queryWrapper);
        String nickName = EmojiParser.parseToUnicode(user.getNickName());
        user.setNickName(nickName); // 将字符转为表情符号
        // 根据邀请openId获取对应的负责人联系方式
        Agent agent = new Agent();
        QueryWrapper<Agent> agentQueryWrapper = new QueryWrapper<>();
        if (user.getYqOpenId() == null || user.getYqOpenId().isEmpty()) {
            // 为空，查询是否有自己的
            QueryWrapper<Agent> q = new QueryWrapper<>();
            q.eq("open_id", user.getWxOpenId());
            agent = agentMapper.selectOne(q);
            // 自己没有取默认的，也就是管理员的
            if (agent == null) {
                agentQueryWrapper.eq("open_id", "oJgFn5YI5Eag3kyRzjKvgKefLOiU");
                agent = agentMapper.selectOne(agentQueryWrapper);
            }
        } else {
            // 取有邀请openId的
            agentQueryWrapper.eq("open_id", user.getYqOpenId());
            agent = agentMapper.selectOne(agentQueryWrapper);
        }

        if (user == null) {
            return ResponseMessage.createByErrorMessage("用户不存在");
        }
        // 填充数据
        UserVo userVo = new UserVo();
        userVo.setUser(user);
        userVo.setAgent(agent);

        return ResponseMessage.createBySuccess(userVo);
    }

    /**
     * 更新客户基本信息
     * 完善用户基本信息
     *
     * @param userUpDto
     * @return
     */
    @Override
    public boolean upUserInfoById(UserUpDto userUpDto) {
        String nickName = EmojiParser.parseToAliases(userUpDto.getNickName()); // 将表情转为字符
        userUpDto.setNickName(nickName); // 设置回去
        // 实体转换 -- 回去试一下这个行不行哈哈哈
        User user = new User();
        BeanUtils.copyProperties(userUpDto, user); // userUpDto -> user
        // User user = dozerMapper.map(userUpDto, User.class);
        // 填充数据
        user.setUpdateTime(new Date());
        int row = userMapper.updateById(user);
        return row <= 0 ? false : true;
    }

    /**
     * 删除客户信息 -- 关联信息
     * 更改用户状态为失效即可
     * @param userId
     * @return
     */
    @Override
    public boolean delUserById(Integer userId) {
        User user = new User();
        user.setUserId(userId);
        user.setIsState(false);

        int row = userMapper.updateById(user);
        return row <= 0 ? false : true;
    }

    /**
     * 检索客户列表信息 -- 分页查询
     * 根据名字模糊查询、学历、用户状态(默认查正常)
     * @return
     */
    @Override
    public Paper<User> getUserList(QueryParam queryParam) {
        Page<User> page = new Page<>();
        page.setCurrent(queryParam.getCurrent());
        page.setSize(queryParam.getSize());

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (queryParam.getUserName() !=null && !queryParam.getUserName().isEmpty()) {
            queryWrapper.like("user_name", queryParam.getUserName());
        }
        if (queryParam.getGraduation() != null && !queryParam.getGraduation().isEmpty()) {
            queryWrapper.eq("graduation", queryParam.getGraduation());
        }
        if (queryParam.getIsState() == null) {
            queryParam.setIsState(true);
        }
        queryWrapper.eq("is_state", queryParam.getIsState());

        Page<User> userPage = userMapper.selectPage(page, queryWrapper);

        List<User> userList = new ArrayList<>();
        for (User u : userPage.getRecords()) {
            u.setNickName(EmojiParser.parseToUnicode(u.getNickName())); // 将emoji特殊字符转回来
            userList.add(u);
        }
        // 数据封装返回
        Paper<User> paper = new Paper<>();
        paper.setCurrent(userPage.getCurrent());
        paper.setSize(userPage.getSize());
        paper.setPages(userPage.getPages());
        paper.setTotal(userPage.getTotal());
        paper.setData(userList);
        return paper;
    }

    /**
     * 更改用户标签
     * 目前使用简陋方式
     * 直接判断，简单粗暴
     * 设定为教学点负责人之后
     * 需要在代理管理中编辑上传负责人联系方式数据
     * @param userId
     * @param userTag 0=管理员，1=教学点负责人，2=普通学员(默认)
     * @return
     */
    @Override
    public ResponseMessage setUserTagById(int userId, int userTag) {
        User user = new User();
        user.setUserId(userId);

        String str = "";
        switch (userTag) {
            case 0:
                // 设定为管理员
                user.setUserTag(userTag);
                user.setYqOpenId(null); // 清除邀请人openId
                str += "请添加联系方式";
            case 1:
                // 设置为教学点负责人 -- 清除邀请人openId
                user.setUserTag(userTag);
                user.setYqOpenId(null); // 清除邀请人openId
                str += "请添加联系方式";
                break;
            case 2:
                // 设定回普通学员
                user.setUserTag(userTag);
                user.setYqOpenId("oJgFn5YI5Eag3kyRzjKvgKefLOiU"); // 默认放自己的
                // 查询原先是否是代理或者管理员
                User u = userMapper.selectById(userId);
                if (u.getUserTag() != 2) {
                    // 是代理或者管理员 -- 删除代理记录
                    QueryWrapper<Agent> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("open_id", u.getWxOpenId());
                    Agent agent = agentMapper.selectOne(queryWrapper);
                    String agentUrl = agent.getErUrl();
                    if (agentUrl != null && !agentUrl.isEmpty()) {
                        ResponseMessage delR = myFileUtils.delFile(agentUrl);
                        if (delR.getStatus() == 1) {
                            // 删除失败
                            return ResponseMessage.createByErrorMessage("删除代理联系方式失败");
                        }
                    }
                    // 删除记录
                    int row = agentMapper.deleteById(agent.getAgentId());
                    if (row <= 0) {
                        return ResponseMessage.createByErrorMessage("代理联系方式记录删除失败");
                    }
                    // 替换所有属于该代理的用户的邀请码为管理员的
                    QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                    userQueryWrapper.eq("yq_open_id", u.getWxOpenId());
                    User user1 = new User();
                    user1.setYqOpenId("oJgFn5YI5Eag3kyRzjKvgKefLOiU");
                    user1.setUpdateTime(new Date());
                    int r = userMapper.update(user1, userQueryWrapper);
                    if (r < 0) {
                        return ResponseMessage.createByErrorMessage("记录替换失败");
                    }
                }
                break;
            default:
                return ResponseMessage.createByErrorMessage("没有该用户角色");
        }
        user.setUpdateTime(new Date());
        // 编辑
        int row = userMapper.updateById(user);
        return row <= 0 ? ResponseMessage.createByErrorMessage("更改异常")
                : ResponseMessage.createBySuccessMessage("更改成功：" + str);
    }
}
